package cn.tedu.egarticle01.controller;

import cn.tedu.egarticle01.base.response.JsonResult;
import cn.tedu.egarticle01.base.response.StatusCode;
import cn.tedu.egarticle01.mapper.UserMapper;
import cn.tedu.egarticle01.pojo.dto.UserArticleDTO;
import cn.tedu.egarticle01.pojo.dto.UserLoginDTO;
import cn.tedu.egarticle01.pojo.entity.Article;
import cn.tedu.egarticle01.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
@Validated
@Slf4j
@RestController
@RequestMapping("/v1/users")
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    @ApiImplicitParam(name = "用户登录", value = "用户登录", required = true)
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        UserVO userVO = userMapper.select(userLoginDTO.getUsername(), userLoginDTO.getPassword());
        log.debug("userVO:{}", userVO);
        if (userVO == null) {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        } else {
            session.setAttribute("user", userVO);
            return JsonResult.ok();
        }
    }

    @PostMapping("/article")
    @ApiOperation(value = "发布文章")
    @ApiImplicitParam(name = "userArticleDTO", value = "用户发布文章信息", required = true)
    public JsonResult publishArticle(@Validated @RequestBody UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO, article);
        article.setUserId(userVO.getId());
        userMapper.insertArticle(article);
        return JsonResult.ok();
    }

    @GetMapping("/selectByArticleId/{aid}")
    @ApiOperation(value = "根据文章id查询文章")
    public JsonResult selectByArticleId(@Range(min=1,max=100,message="文章id必须在1到100之间") @PathVariable Long aid) {
        userMapper.selectByArticleId(aid);
        return JsonResult.ok();
    }


}
